package com.yuuzy.qqclient.service;

import com.yuuzy.qqcommon.Message;
import com.yuuzy.qqcommon.MessageType;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.SQLOutput;

public class ClientConnectServerThread extends Thread{
	//该线程需要持有Socket
	private Socket socket;
	public ClientConnectServerThread(Socket socket){
		this.socket = socket;
	}

	public Socket getSocket() {
		return socket;
	}

	@Override
	public void run() {
		//因为Thread需要在后台和服务器通信，所以我们需要while循环
		while (true){
			try {
				//没有消息会阻塞
				ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
				Message ms = (Message) objectInputStream.readObject();
				//判断这个message类型，然后做相应的业务处理
				//如果是读取到的是 服务端返回的在线用户列表
				if (ms.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND)) {
					//取出在线列表信息，并显示
					//规定：用空格分隔用户
					String[] onlineUsers = ms.getContent().split(" ");
					System.out.println("=======当前在线用户列表========");
					for (int i = 0; i < onlineUsers.length; i++) {
						System.out.println("用户：" + onlineUsers[i]);
					}
				} else if (ms.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {
					//私聊
					System.out.println("\n" + ms.getSender() + "对你说：" + ms.getContent());
				} else if (ms.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)) {
					//群发
					System.out.println("\n" + ms.getSender() + "对大家说：" + ms.getContent());
				} else if (ms.getMesType().equals(MessageType.MESSAGE_FILE_MES)) {
					//文件
					System.out.println("\n" + ms.getSender() + "向你发送文件存于：" + ms.getDest());
					//取出message的文件字节数组，通过文件流写出到磁盘
					FileOutputStream fileOutputStream = new FileOutputStream(ms.getDest());
					fileOutputStream.write(ms.getFileBytes());
					fileOutputStream.close();
					System.out.println("保存文件成功");
				} else {
					System.out.println("其他类型");
				}
			} catch (IOException |
			         ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
